import sys
import os
import importlib


class ModuleManage(object):
    def __init__(self, root):
        self.root = root
        sys.path.append(root + '../')
        sys.path.append(root + '../lib/')
        sys.path.append(root + '../server/')
        sys.path.append(root)
        self._dict = {}

    def reload_file(self, file_name_list):
        for file_name in file_name_list:
            if file_name in self._dict:
                importlib.reload(self._dict[file_name])
                del self._dict[file_name]
        print(f"成功reload file->{len(file_name_list)}======{file_name_list}")

    def reload(self):
        _reloadList = []
        # 只reload接口文件
        for model_name in list(self._dict.keys()):
            if "fun" in model_name or model_name in ["task.taskclass"]:
                continue
            if not (
                    hasattr(self._dict[model_name], "proc") or
                    self._dict[model_name].__dict__.get("isreload")
            ):
                continue
            try:
                importlib.reload(self._dict[model_name])
                # print(f"api reload......{modelName}")
                _reloadList.append(model_name)
            except Exception as e:
                print(f"api reload[{model_name}] error!! {e}")
                del self._dict[model_name]

        print(f"成功reload api->{len(_reloadList)}======{_reloadList}")

    def preload(self):
        _root = os.path.abspath(os.path.dirname(__file__)).replace('\\', '/').split("lib")[0]
        _gameRoot = _root + 'game/'
        for folder in os.listdir(_gameRoot):
            _toPath = _gameRoot + str(folder)
            # 不是文件夹
            if not os.path.isdir(_toPath):
                continue
            _fileList = os.listdir(_toPath)
            for file in _fileList:
                if file.find('fun') != -1 and file.endswith(".py") and not file.startswith("."):
                    self.load("{}.{}".format(folder, file.replace('.py', '')))

        # print("modulemanage preload success!!")

    def load(self, name):
        # 自动加载模块
        if name not in self._dict:
            if name not in sys.modules:
                try:
                    if name.find('.') == -1:
                        self._dict[name] = __import__(name)
                    else:
                        name_split = name.split('.')
                        self._dict[name] = __import__(name, fromlist=(name_split[-1],))
                except ModuleNotFoundError:
                    print(f"ModuleManage 加载[{name}]失败 err=>[{ModuleNotFoundError}]")
                except Exception as e:
                    print(e)
            else:
                self._dict[name] = sys.modules[name]

        return self._dict.get(name, None)

    def __getitem__(self, name):
        return self.load(name)

    def __getattr__(self, name):
        return self.load(name)
